using System;
using System.ComponentModel.Design;
using Needle.Core.Activation;
using Needle.Core.Lifetime;
using Needle.Framework;
using Needle.Utils;
using Needle.Utils.Extensions;

namespace Needle.Core.Resolver
{

    /// <summary>
    /// This class does simple resolution of dependencies,
    /// It tries to create a new reflection based activator and binding for every dependency id is does not know about.
    /// </summary>
    public class SimpleResolver : LifetimeComponent, IResolver
    {

        #region IResolver Members
       
        /// <summary>
        /// Returns an instance for the given dependency id.
        /// </summary>
        public object GetInstance(InstanceId id)
        {
            Ensure.NotDisposed(this);
            Ensure.NotNull(id, "id");
            try
            {
                ILifetimeManager lifetimeManager = GetService<ILifetimeManager>();
                object instance = lifetimeManager.GetInstance(id);
                if (instance == null)
                {
                    IActivationManager activationManager = GetService<IActivationManager>();
                    instance = activationManager.CreateInstance(id);
                }
                return instance;
            }
            catch (Exception ex)
            {
                throw new InstanceResolutionException("Instance could not be resolved for id " + id.ToString(), ex);
            }

        }

        #endregion
        /// <summary>
        /// Begins initialization of the SimpleResolver.
        /// </summary>
        public override void BeginInit()
        {
            base.BeginInit();
            IServiceContainer sc = null;
            sc = GetService<IServiceContainer>();
            if (sc != null)
                sc.AddService<IResolver>(this, true);
        }

    }
}
